package com.fast.develop.configuration.persistence;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.fast.develop.core.io.db.DbResourceRepository;
import java.util.List;
import java.util.UUID;

/**
 * @author 莫寅
 * @createTime 2022-06-23 12:52
 * @desc：
 */

public class DbResourceRepositoryImpl implements DbResourceRepository {


    private ResourceFileRepository resourceFileRepository;

    public DbResourceRepositoryImpl(ResourceFileRepository resourceFileRepository) {
        this.resourceFileRepository = resourceFileRepository;
    }

    @Override
    public void createFile(String path, byte[] content) {
        ResourceFileEntity dbResource = resourceFileRepository.findByPath(path);

        if(dbResource == null){
            String name = FileUtil.getName(path);

            ResourceFileEntity resourceFileEntity = new ResourceFileEntity();
            resourceFileEntity.setId(UUID.randomUUID().toString());
            resourceFileEntity.setContent(StrUtil.utf8Str(content));
            resourceFileEntity.setFolder(false);
            resourceFileEntity.setName(name);
            resourceFileEntity.setPath(path);
            resourceFileRepository.save(resourceFileEntity);
        }else{
            dbResource.setContent(StrUtil.utf8Str(content));
            resourceFileRepository.save(dbResource);
        }
    }


    @Override
    public void createFolder(String path) {
        ResourceFileEntity dbResource = resourceFileRepository.findByPath(path);

        if(dbResource == null){
            String name = FileUtil.getName(path);
            ResourceFileEntity resourceFileEntity = new ResourceFileEntity();
            resourceFileEntity.setId(UUID.randomUUID().toString());
            resourceFileEntity.setContent(null);
            resourceFileEntity.setFolder(true);
            resourceFileEntity.setName(name);
            resourceFileEntity.setPath(path);
            resourceFileRepository.save(resourceFileEntity);
        }
    }

    @Override
    public List<ResourceFileEntity> list() {
        return resourceFileRepository.findAll();
    }

    @Override
    public void deleteByPath(String path) {
        resourceFileRepository.deleteByPath(path);
    }

    @Override
    public void rename(String path, String newName) {
    }
}
